/*
 * Created by IntelliJ IDEA.
 * User: amrk
 * Date: 14/02/2005
 * Time: 23:25:23
 */
package com.talios.jira.browser;

import com.intellij.openapi.diagnostic.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Comparator;

public class ReflectiveIssueComparator implements Comparator {
    private static final Logger LOGGER = Logger.getInstance(JiraIssuesTableModel.class.toString());

    private String[] fields;

    public ReflectiveIssueComparator(String field) {
        this.fields = new String[]{field};
    }

    public ReflectiveIssueComparator(String[] fields) {
        this.fields = fields;
    }

    public int compare(Object o1, Object o2) {

        int result = 0;
        for (String field : fields) {
            result = compare(o1, o2, field);
            if (result != 0) {
                return result;
            }
        }
        return result;
    }

    private int compare(Object o1, Object o2, String field) {
        if (o1 == null || o2 == null) {
            return 0;
        }

        String methodName = ReflectiveTools.buildGetter(field);
        try {
            Method method = JiraItem.class.getMethod(methodName, new Class[]{});
            Comparable m1 = (Comparable) method.invoke(o1);
            Comparable m2 = (Comparable) method.invoke(o2);

            return m1 == null ? 1 : m2 == null ? 0 : m1.compareTo(m2);
        } catch (NoSuchMethodException e) {
            LOGGER.error("No getter for " + field, e);
        } catch (IllegalAccessException e) {
            LOGGER.error("No getter for " + field, e);
        } catch (InvocationTargetException e) {
            LOGGER.error("No getter for " + field, e);
        }

        return 0;
    }

}